package com.hundsun.documentripper.error;

import com.hundsun.documentripper.domain.dto.BaseResponse;
import lombok.extern.slf4j.Slf4j;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.springframework.core.annotation.Order;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;

/**
 * Note：
 *
 * @author ：mengjw
 * @description：异常捕捉切面
 * @date ：Created in 2020/6/29
 * @copyright : 恒生电子股份有限公司
 */
@Aspect
@Slf4j
@Order(-1)
@Component
public class ErrorCatcherAspect {


    @Around("@annotation(errorCatcher)")
    public Object catchError(ProceedingJoinPoint joinPoint, ErrorCatcher errorCatcher) throws Throwable {
        try {
            return joinPoint.proceed();
        } catch (Throwable throwable) {
            log.error(throwable.getMessage(), throwable);
            BaseResponse<Void> baseResponse = new BaseResponse<>();
            baseResponse.setReturnCode(-1);
            if (throwable instanceof BaseException) {
                // 如果是BaseException类型的，则获取异常进行处理
                baseResponse.setErrorCode(((BaseException) throwable).getErrorCode());
                baseResponse.setErrorMessage(((BaseException) throwable).getErrorMessage());
            } else {
                // 如果是异常错误，则记录错误并封装错误抛出
                baseResponse.setErrorCode(errorCatcher.code());
                if (StringUtils.isEmpty(errorCatcher.message())) {
                    baseResponse.setErrorMessage(ErrorMessage.getMessage(errorCatcher.code()));
                } else {
                    baseResponse.setErrorMessage(errorCatcher.message());
                }
            }
            return baseResponse;
        }
    }

}